package com.mediastory.spsserver.system.auth;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Controller;

import com.mediastory.spsserver.users.domain.Users;
import com.mediastory.spsserver.users.service.UsersSvc;

/**
 * @author Jaewon Choi
 */

@Controller("authSuccessHandler")
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
    private UsersSvc usersSvc;
	
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		UserDetails userDetails = (UserDetails)authentication.getPrincipal();
		String userId = userDetails.getUsername();
		
		try {
			Users users = usersSvc.findbyAuth(userId);
			// 세션 생성
			HttpSession session = request.getSession();
			session.setAttribute("userId", users.getId());
			session.setAttribute("userNm", users.getName());
			session.setAttribute("userRole", users.getAuthority());
			session.setAttribute("cIdx", users.getcIdx());
			session.setAttribute("cName", users.getcName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			throw new ServletException("[ERROR] 이용자 정보를 가져오지 못했습니다.");
		}

		super.onAuthenticationSuccess(request, response, authentication);
	}    
}